package common

import (
	"fmt"
	"strings"
	"time"

	log "github.com/sirupsen/logrus"

	"github.com/spf13/viper"
)

var (
	expiry string
	Config string
	Port   string
)

func Tparse(parts []string) []string {
	who := make([]string, 0, 4)
	if len(parts) == 3 {
		for i, part := range parts {
			right := strings.TrimRight(part, "\x0d")
			split := strings.Split(right, " ")
			length := len(split)
			d := split[length-1]

			t, err := time.ParseInLocation("2006-01-02T15:04:05Z", d, time.Local)
			if err != nil {
				fmt.Println(err)
			}
			h, _ := time.ParseDuration("1h")
			t_ := t.Add(8 * h)

			if i == 2 {
				//处理剩余过期时间的逻辑
				s := time.Now()
				duration := t_.Sub(s)
				expiry = fmt.Sprintf("%.2f", duration.Hours())
			}
			n := t_.Format("2006-01-02 15:04:05")
			who = append(who, n)
		}
	} else {
		for i, v := range parts {
			s := strings.Split(v, ": ")
			who = append(who, s[len(s)-1])
			if i == 0 {
				// 这种查询方式没有更新时间，所以手动添加注册时间为更新时间
				who = append(who, s[len(s)-1])
			}
		}
		t_, err := time.ParseInLocation("2006-01-02 15:04:05", who[2], time.Local)
		if err != nil {
			fmt.Println(err)
		}
		t_now := time.Now()
		duration := t_.Sub(t_now)
		expiry = fmt.Sprintf("%.2f", duration.Hours())
	}

	who = append(who, expiry)
	return who
}

func MultiParse(names []string) [][]string {
	domainList := make([][]string, 0)
	for _, name := range names {
		for _, v := range WHOIS_SERVER {
			s, err := Query(name, v)
			if err != nil {
				log.Panicln(err)
				continue
			}
			if len(s) == 0 {
				continue
			}

			s2 := Tparse(s)
			s2 = append(s2, name)
			domainList = append(domainList, s2)
			log.Printf("☺ 解析成功了，域名: %s, 成功服务器: %s", name, v)
			break
		}

	}
	return domainList
}

func NameParse() []string {
	if Config == "" {
		viper.SetConfigName("dnsexpiry")
		viper.SetConfigType("yaml")
		viper.AddConfigPath("/etc")
	} else {
		configList := strings.Split(Config, "/")
		pathl := configList[:len(configList)-1]
		path := strings.Join(pathl, "/")
		viper.SetConfigName(configList[len(configList)-1])
		viper.SetConfigType("yaml")
		viper.AddConfigPath(path)
	}

	err := viper.ReadInConfig()
	if err != nil {
		log.Panicf("read config from file failed, err: %s", err)
	}
	return viper.GetStringSlice("names")
}
